﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Dracham.Classes
{
    public class MessageHandler
    {
        public static MessageHandler Instance
        {
            get
            {
                return MessageHandlerCreator.Instance;
            }
        }

        public void HandleMessage(DrachamNetwork client)
        {
            string sesKey = client.ReceiveString(36);

            int msgLength = client.ReceiveInt32(10);
            String msg = client.ReceiveString(msgLength);

            Account acc = GameWorld.Accounts.SingleOrDefault(a => a.Client == client && a.SessionKey == sesKey);

            if (String.IsNullOrEmpty(msg)) return;

            if (msg.Substring(0, 1) == ".")
            {
                msg += " ";
                if (acc.AccountType == (int)AccessLevels.GameMaster || acc.AccountType == (int)AccessLevels.Administrator)
                {
                    String cmd = this.ExtractCommand(ref msg);

                    if (cmd == "teleport")
                    {
                        string x = this.ExtractCommand(ref msg);
                        string y = this.ExtractCommand(ref msg);
                        string zoneId = this.ExtractCommand(ref msg);

                        Position p = new Position(float.Parse(x), float.Parse(y), zoneId);
                        acc.CurrentCharacter.Move(p);
                    }
                }
            }
            else
            {
                List<NetworkParameter> netParams = new List<NetworkParameter>();
                netParams.Add(new NetworkParameter(acc.CurrentCharacter.Name, 20));
                netParams.Add(new NetworkParameter(msgLength.ToString(), 10));
                netParams.Add(new NetworkParameter(msg, msgLength));

                foreach (Account account in acc.CurrentCharacter.Position.Zone.GetCharactersInZone())
                {
                    account.Client.Invoke(MessageType.ChatMessage, netParams.ToArray());
                }
            }
        }

        public String ExtractCommand(ref String message)
        {
            String cmd = message.Substring(0, message.IndexOf(" ", 0));
            message = message.Remove(0, cmd.Length + 1);
            return cmd;
        }
    }

    public static class MessageHandlerCreator
    {
        private static readonly MessageHandler instance = new MessageHandler();

        public static MessageHandler Instance
        {
            get
            {
                return instance;
            }
        }
    }
}
